﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Intorise.Tools.Process
{
    struct COPYDATASTRUCT
    {
        public IntPtr dwData;
        public int cbData;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpData;
    }

    public class ProcessMessage
    {
        public const int WM_COPYDATA = 0x004A;

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(
        int hWnd, // handle to destination window
        int Msg, // message
        int wParam, // first message parameter
        ref COPYDATASTRUCT lParam // second message parameter
        );

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string
        lpWindowName);

        /// <summary>
        /// 向指定的窗口发送消息
        /// </summary>
        /// <param name="windowName">窗口名称</param>
        /// <param name="text">要发送的消息</param>
        /// <returns></returns>
        public static bool SendMessage(string windowName,string text)
        {
            int WINDOW_HANDLER = FindWindow(null, windowName);
            if (WINDOW_HANDLER == 0)
            {
                return false;
            }
            else
            {
                byte[] sarr = System.Text.Encoding.Default.GetBytes(text);
                int len = sarr.Length;
                COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)100;
                cds.lpData = text;
                cds.cbData = len + 1;
                SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds);
                return true;
            }
        }

        /// <summary>
        /// 读取ProcessMessage类发送过来的消息(如果有)，本方法应该在Form.DefWndProc中调用
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        public static void ReadMessage(ref Message m,ref string message)
        {
            switch (m.Msg)
            {
                case WM_COPYDATA:
                    COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                    Type mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    message= mystr.lpData;
                    break;
            }
        }
    }
}
